package org.song.util;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.song.exception.myException.CommonException;
import org.song.mapper.UserMapper;
import org.song.model.entity.UserEntity;
import org.song.model.threadlocal.WebContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author song
 * @date 2022/3/20 15:07
 * 用户工具类
 */
@Component( value = "userUtil" )
@Slf4j
public final class UserUtil {

    // HTTP认证请求头KEY
    public static final String AUTHORIZATION_HEAD = "Authorization";

    @Autowired( required = true )
    @Qualifier( value = "jwtTokenUtil")
    private static JwtTokenUtil jwtTokenUtil;

    @Autowired( required = true )
    @Qualifier( value = "userMapper")
    private UserMapper userMapper;

    /**
     * 获取当前用户
     * @return
     */
    @NonNull
    public UserEntity getOnlineUser() {
        // 从ThreadLocal中获取本次请求实例，从请求头中获取用户token，解析token取出用户信息返回
        return Optional.ofNullable( WebContextUtil.getCurrentRequest() )
                .map( (currentRequest) -> currentRequest.getHeader(AUTHORIZATION_HEAD) )
                .map ( (token) -> {
                    // 解析token , 根据用户名获取用户
                    return userMapper.getUserByUsername( jwtTokenUtil.getUsernameFromToken(token) );
                } )
                .orElseThrow( () -> {
                    log.error("请求头为空用户未登录");
                    return new CommonException("请登录~");
                } );
    }

}
